<?php

/**
 * 生成订单号
 */
function order_create_no(){
	return date('YmdHis', time()).rand(8, true);
}

function add_money_log($title,$content,$num,$uid,$type=1){
	// type 1是买入2卖出；cate 1消费2推广
	$data['uid'] = $uid;
	$data['title'] = $title;
	$data['note'] = $content;
	$data['num'] = $num;
	$data['type'] = $type;
	$data["add_time"] = now_time();
	db('money')->insert($data);
}
	
function add_coin_log($title,$content,$num,$uid,$type=1){
	$data['uid'] = $uid;
	$data['title'] = $title;
	$data['note'] = $content;
	$data['num'] = $num;
	$data['type'] = $type;
	$data["add_time"] = now_time();
	db('coin')->insert($data);
}

function get_day($datetime) {
	$startdate = strtotime($datetime);
	$days = (time() - $startdate) / 86400;
	$days = 20 - round($days);
	if($days < 0){
		$days = 0;
	}
	return $days;
}

function format_name($user_name){
	if($user_name == ""){
		return '未填写';
	}
	if(mb_strlen($user_name, 'UTF-8') < 2){
		return $user_name;
	}
	$strlen = mb_strlen($user_name, 'utf-8');
    $firstStr = mb_substr($user_name, 0, 1, 'utf-8');
    $lastStr = mb_substr($user_name, -1, 1, 'utf-8');
    return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
}

function format_mobile($mobile) {
	if ($mobile) {
		$start = substr($mobile, 0, 3);
		$end = substr($mobile, 7, 4);
		return $start . '****' . $end;
	}
}


/**
 * 获得配置
 */
function get_config($name){
	if(cache($name)){
		return cache($name);
	}else{
		$site_config = db('system')->field('value')->where('name', $name)->find();
	    $site_config = unserialize($site_config['value']);
		return $site_config;
	}
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author rainfer <81818832@qq.com>
 */
function format_bytes($size, $delimiter = '') {
    $units = array(' B', ' KB', ' MB', ' GB', ' TB', ' PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}
function format_idcard($idcard) {
	if ($idcard) {
		$start = substr($idcard, 0, 3);
		$end = substr($idcard, 14, 4);
		return $start . '********' . $end;
	}
}

function to_day_time($ts) {
	$dd = floor($ts / 60 / 60 / 24);
	//计算剩余的天数
	$hh = $ts / 60 / 60 % 24;
	//计算剩余的小时数
	$mm = $ts / 60 % 60;
	//计算剩余的分钟数
	$hh = check_time($hh);
	$mm = check_time($mm);
	return $dd . '天' . $hh . '时' . $mm . '分';
}

function to_day($ts) {
	$dd = floor($ts / 60 / 60 / 24);
	//计算剩余的小时数
	$hh = $ts / 60 / 60 % 24;
	//计算剩余的小时数
	$hh = check_time($hh);
	return $dd . '天' . $hh . '时';
}

function to_timer($ts) {
	$hh = $ts / 60 / 60 % 24;
	//计算剩余的小时数
	$mm = $ts / 60 % 60;
	//计算剩余的分钟数
	$hh = check_time($hh);
	$mm = check_time($mm);
	return $hh . '时' . $mm . '分';
}

function check_time($i) {
	if ($i < 10) {
		$i = "0" . $i;
	}
	return $i;
}

/**
 * 获取当前request参数数组,去除值为空
 * @return array
 */
function get_query() {
	$param = request()->except(['s']);
	$rst = array();
	foreach ($param as $k => $v) {
		if (!empty($v)) {
			$rst[$k] = $v;
		}
	}
	return array('query' => $rst);
}

/**
 * action写入
 */
function update_member($uid) {
	$data['id'] = $uid;
	$data['qiang_time'] = now_time();
	$result = db("member")->update($data, ['id' => $uid]);
}

/*
 * 加密--32位密码
 */
function md5_salt($password) {
	return md5(crypt($password, config('salt')));
}

/**
 * 返回格式化后的当前时间
 */
function now_time() {
	return date('Y-m-d H:i:s', time());
}

//发送短信
function sendsms($sign,$mobile,$tempid,$name,$value){
	$cut_time = now_time();
	include_once ('./extend/smsapi/smsDemo.php');
	$msg=sendMess($sign,$mobile,$tempid,$name,$value);
	if($msg->Message=="OK") {
		$data['mobile'] 	= $mobile;
		$data[$name] 		= $value;
		$data['add_time'] 	= $cut_time;
		$data['message'] 	= '发送成功';
		db('sms_code')->insert($data);
		return true;
	}else{
		$data['mobile'] 	= $mobile;
		$data[$name] 		= $value;
		$data['add_time'] 	= $cut_time;
		$data['result'] 	= 0;
		$data['message'] 	= '发送失败:'.$msg->Message;
		db('sms_code')->insert($data);
		$err=$msg->Message;
		return false;
	}
}

//发送短信
function send_sms($phone, $template_id, $code) {
	$app_config = config('alidayu');
	include_once ('./extend/taobao/TopSdk.php');
	date_default_timezone_set('Asia/Shanghai');
	$c = new TopClient;
	//	$c -> format = 'json';
	//	$c -> simplify = true;
	$c->appkey = $app_config['app_key'];
	//  23613152
	$c->secretKey = $app_config['app_secret'];
	//  be075d72e8767e336b778b47b6a8f68e
	$req = new AlibabaAliqinFcSmsNumSendRequest;
	$req->setSmsType("normal");
	$req->setSmsFreeSignName($app_config['app_sign']);
	$req->setSmsParam('{"code":"'.$code.'","product":"龙信云商铺"}');
	//$req->setSmsParam('{"code":"' . $code . '"}');
	$req->setRecNum($phone);
	$req->setSmsTemplateCode($template_id);
	$resp = $c->execute($req);
	return $resp;
}

/**验证码*/
 function check_sendcode($mobile, $code){
		$where['mobile'] = $mobile;
		$where['code'] = $code;
		$where['message'] = '发送成功';
		$result =db('sms_code')->where($where)->find();
		// 10分钟有效期
		if(time() - strtotime($result['add_time']) > 600){
			return 2;
		}
		if($code == $result['code']){
			return 1;
		}else{
			return -1;
		}
	}

/**
 * 数组里删除指定key的数据
 */
function array_remove($data, $key) {
	if (!array_key_exists($key, $data)) {
		return $data;
	}
	$keys = array_keys($data);
	$index = array_search($key, $keys);
	if ($index !== FALSE) {
		array_splice($data, $index, 1);
	}
	return $data;
}

/**
 * 数组层级缩进转换
 * @param array $array
 * @param int   $pid
 * @param int   $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1) {
	static $list = [];
	foreach ($array as $v) {
		if ($v['pid'] == $pid) {
			$v['level'] = $level;
			$list[] = $v;
			array2level($array, $v['id'], $level + 1);
		}
	}

	return $list;
}

/**
 * 构建层级（树状）数组
 * @param array  $array 要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid 父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid = 'pid', $child_key_name = 'children') {
	$counter = array_children_count($array, $pid);
	if ($counter[0] == 0)
		return false;
	$tree = [];
	while (isset($counter[0]) && $counter[0] > 0) {
		$temp = array_shift($array);
		if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
			array_push($array, $temp);
		} else {
			if ($temp[$pid] == 0) {
				$tree[] = $temp;
			} else {
				$array = array_child_append($array, $temp[$pid], $temp, $child_key_name);
			}
		}
		$counter = array_children_count($array, $pid);
	}

	return $tree;
}

/**
 * 子元素计数器
 * @param $array
 * @param $pid
 * @return array
 */
function array_children_count($array, $pid) {
	$counter = [];
	foreach ($array as $item) {
		$count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
		$count++;
		$counter[$item[$pid]] = $count;
	}

	return $counter;
}

/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name) {
	foreach ($parent as &$item) {
		if ($item['id'] == $pid) {
			if (!isset($item[$child_key_name]))
				$item[$child_key_name] = [];
			$item[$child_key_name][] = $child;
		}
	}

	return $parent;
}

/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name) {
	$result = false;
	if (is_dir($dir_name)) {
		if ($handle = opendir($dir_name)) {
			while (false !== ($item = readdir($handle))) {
				if ($item != '.' && $item != '..') {
					if (is_dir($dir_name . DS . $item)) {
						delete_dir_file($dir_name . DS . $item);
					} else {
						unlink($dir_name . DS . $item);
					}
				}
			}
			closedir($handle);
			if (rmdir($dir_name)) {
				$result = true;
			}
		}
	}

	return $result;
}

/**
 * 判断是否为手机访问
 * @return  boolean
 */
function is_mobile() {
	static $is_mobile;

	if (isset($is_mobile)) {
		return $is_mobile;
	}

	if (empty($_SERVER['HTTP_USER_AGENT'])) {
		$is_mobile = false;
	} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false) {
		$is_mobile = true;
	} else {
		$is_mobile = false;
	}

	return $is_mobile;
}
